<template>
  <div class="math-practice-system">
    <!-- 顶部导航 -->
    <el-menu mode="horizontal" :default-active="activeTab" @select="handleTabChange">
      <el-menu-item index="practice">练习模式</el-menu-item>
      <el-menu-item index="wrong-answers">错题本</el-menu-item>
    </el-menu>

    <!-- 练习模式 -->
    <div v-if="activeTab === 'practice'" class="practice-mode">
      <div class="practice-header">
        <h1>数学练习</h1>
        <div class="practice-controls">
          <el-select v-model="practiceMode" placeholder="选择练习模式">
            <el-option label="顺序练习" value="sequential"></el-option>
            <el-option label="随机练习" value="random"></el-option>
            <el-option label="错题重练" value="wrong-answers"></el-option>
          </el-select>
          
          <el-button 
            type="primary" 
            @click="startPractice"
            :loading="loadingPractice"
            :disabled="loadingPractice"
          >
            开始练习
          </el-button>
        </div>
      </div>
      
      <!-- 练习统计 -->
      <div class="practice-stats">
        <el-card shadow="never">
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value">{{ stats.totalPracticed }}</div>
              <div class="stat-label">已练习</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.correctRate }}%</div>
              <div class="stat-label">正确率</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.wrongCount }}</div>
              <div class="stat-label">错题数</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 错题本 -->
    <div v-if="activeTab === 'wrong-answers'" class="wrong-answers">
      <h1>错题本</h1>
      
      <el-table 
        :data="wrongQuestions"
        style="width: 100%"
        v-loading="loadingWrong"
      >
        <el-table-column prop="content" label="题目" min-width="300">
          <template #default="{row}">
            <div class="question-content" v-html="row.content"></div>
          </template>
        </el-table-column>
        
        <el-table-column label="你的答案" width="120" align="center">
          <template #default="{row}">
            <span :class="{'wrong-answer': !row.isCorrect}">
              {{ row.userAnswer }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="answer" label="正确答案" width="120" align="center" />
        
        <el-table-column label="操作" width="120" align="center">
          <template #default="{row}">
            <el-button size="small" type="primary" @click="startPracticeWithQuestion(row.id)">重做</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 全局状态
const activeTab = ref('practice')
const practiceMode = ref('sequential')
const loadingPractice = ref(false)
const stats = reactive({
  totalPracticed: 0,
  correctRate: 0,
  wrongCount: 0
})

// 练习相关状态
const practiceQuestions = ref([])

// 错题本相关
const wrongQuestions = ref([])
const loadingWrong = ref(false)

// API配置
const api = axios.create({
  baseURL: 'http://192.168.43.173:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': localStorage.getItem('token') || ''
  }
})

// 方法定义
const fetchWrongQuestions = async () => {
  try {
    loadingWrong.value = true
    const response = await api.get('/api/practice/wrong-answers')
    wrongQuestions.value = response.data?.data || []
    stats.wrongCount = wrongQuestions.value.length
  } catch (error) {
    ElMessage.error('获取错题失败')
    console.error('获取错题失败:', error)
  } finally {
    loadingWrong.value = false
  }
}

const fetchPracticeStats = async () => {
  try {
    const response = await api.get('/api/practice/stats')
    if (response.data?.code === 200) {
      Object.assign(stats, response.data.data)
    }
  } catch (error) {
    console.error('获取练习统计失败:', error)
  }
}

const fetchQuestions = async (questionIds) => {
  try {
    loadingPractice.value = true
    const response = await api.get('/api/questions', {
      params: {
        ids: questionIds.join(',')
      }
    })
    
    if (response.data?.code === 200 && Array.isArray(response.data.data?.list)) {
      return response.data.data.list
    } else {
      throw new Error('获取题目失败')
    }
  } catch (error) {
    ElMessage.error(error.message)
    console.error('获取题目失败:', error)
    return []
  } finally {
    loadingPractice.value = false
  }
}

// 在原组件中修改startPractice方法
const startPractice = async (questionIds) => {
  try {
    loadingQuestions.value = true
    let ids = questionIds
    
    if (!ids || !ids.length) {
      if (practiceMode.value === 'wrong-answers') {
        ids = wrongQuestions.value.map(q => q.id)
        if (!ids.length) {
          ElMessage.warning('错题本为空')
          return
        }
      } else {
        const response = await api.get('/api/questions/ids')
        ids = response.data?.data || []
      }
    }
    
    if (!ids.length) {
      ElMessage.warning('没有可练习的题目')
      return
    }
    
    const detailResponse = await api.get('/api/questions', {
      params: { ids: ids.join(',') }
    })
    
    if (detailResponse.data?.code === 200 && Array.isArray(detailResponse.data.data?.list)) {
      let questions = detailResponse.data.data.list
      
      if (practiceMode.value === 'random') {
        questions = questions.sort(() => Math.random() - 0.5)
      }
      
      router.push({
        name: 'PracticePage',
        state: {
          questions,
          practiceMode: practiceMode.value
        }
      })
    }
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    loadingQuestions.value = false
  }
}

const startPracticeWithQuestion = async (questionId) => {
  const questions = await fetchQuestions([questionId])
  if (questions.length > 0) {
    // 跳转到练习页面并传递题目数据
    router.push({
      name: 'lxym',
      state: {
        questions: questions,
        practiceMode: 'sequential'
      }
    })
  }
}

const handleTabChange = (tab) => {
  activeTab.value = tab
  if (tab === 'wrong-answers') {
    fetchWrongQuestions()
  } else if (tab === 'practice') {
    fetchPracticeStats()
  }
}

// 初始化
onMounted(() => {
  fetchPracticeStats()
})
</script>

<style scoped>
.math-practice-system {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.practice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.practice-controls {
  display: flex;
  gap: 15px;
}

.practice-stats {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  text-align: center;
}

.stat-item {
  padding: 15px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.wrong-answer {
  color: #F56C6C;
  text-decoration: line-through;
}

.question-content {
  line-height: 1.6;
}
</style>